package org.streets.eis.component.grid;

import org.apache.wicket.ajax.AjaxEventBehavior;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.markup.ComponentTag;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.panel.Panel;

import com.inmethod.grid.datagrid.DataGrid;

/**
 * 可改变每页显示记录的
 *
 */
public class DefualtNavigatorLabelPanel extends Panel {
	private static final long serialVersionUID = 1L;
	
	private final DataGrid table;

	public DefualtNavigatorLabelPanel(final String id, final DataGrid table) {
		super(id);
		this.table = table;
	}
	
	@Override
	protected void onBeforeRender() {
		super.onBeforeRender();
		removeAll();
		add(new Label("label",getLabelString()));
		WebMarkupContainer perPageCount = new WebMarkupContainer("input") {
			private static final long serialVersionUID = 1L;
			@Override
			protected void onComponentTag(ComponentTag tag) {
				super.onComponentTag(tag);
				tag.put("title", "输入新的每页显示记录数,按回车确认.");
				tag.put("value",getPageSize());
			}
		};
		add(perPageCount);

		perPageCount.add(new AjaxEventBehavior("onkeydown") {
			private static final long serialVersionUID = 1L;
			@Override
			protected void onEvent(AjaxRequestTarget target) {
				String ps = getRequest().getParameter("ps");
				getGrid().setRowsPerPage(Integer.valueOf(ps).intValue());
				target.addComponent(getPage());
			}

			@Override
			public CharSequence getCallbackUrl(final boolean onlyTargetActivePage){
				return super.getCallbackUrl(onlyTargetActivePage) + "&ps='+this.value+'";
			}
			
			@Override
			protected CharSequence getEventHandler(){
				return "if(event.keyCode!=13){return true;}" +
						"var v=parseInt(this.value);if(isNaN(v)){return false;}" +
						"if(v<=0||v>100){this.value='"+getPageSize()+"';return false;}"+
						super.getEventHandler();
			}

		});
	}

	public String getRecCount() {
		int total = table.getTotalRowCount();
		return total != -1 ? "" + total : "未知";
	}

	public int getPageNo() {
		return table.getCurrentPage() + 1;
	}

	public int getPageCount() {
		return table.getPageCount();
	}	
	
	public String getLabelString(){
		return String.format("(第%d页/共%d页) 共有%s条记录", getPageNo(),getPageCount(),getRecCount());
	}
	
	public int getPageSize(){
		return table.getRowsPerPage();
	}
	
	public DataGrid getGrid(){
		return table;
	}

}
